<template>
  <div>
    <a-modal
      :visible="visible"
      @before-ok="handleOk"
      @ok="handleCancel"
      @cancel="handleCancel"
      ok-text="提交"
      cancel-text="取消"
      title="不予处理"
      title-align="start"
      unmount-on-close
    >
      <a-form
        :model="formValue"
        @submit="handleSubmit"
        layout="vertical"
        size="large"
        ref="formRef"
      >
        <a-form-item
          field="accept_msg"
          label="说明备注"
          :rules="[
            { required: true, message: '不予处理理由必填' }
          ]"
        >
          <a-textarea
            v-model="formValue.accept_msg"
            placeholder="请输入不予受理的原因"
            allow-clear
            :max-length="200"
            show-word-limit
            :auto-size="{ minRows: 4, maxRows: 4 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { watch, ref } from 'vue'
import { cloneDeep } from 'lodash-es'
import { useRoute } from 'vue-router'

import { useApi } from '/@/api'
import { noop } from '/@/utils/helper'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  onClose: {
    type: Function,
    default: () => noop
  }
})
const visible = ref(false)

const route = useRoute()

const formRef = ref()
const formInitValue = {
  status: 'CANCELLED',
  accept_msg: null
}
const formValue = ref(cloneDeep(formInitValue))

watch(
  () => props.visible,
  v => {
    visible.value = v
  }, { immediate: true })

  function handleCancel() {
  if (formRef.value?.resetFields) {
    formRef.value?.resetFields()
  }
  formValue.value = cloneDeep(formInitValue)
  props.onClose()
  visible.value = false
}

function handleOk(done) {
  if (formRef.value?.handleSubmit) {
    return formRef.value?.handleSubmit(done)
  }
}

function handleSubmit({ values, errors }, done = noop) {
  if (errors) return done(false)
  useApi()
    .post(
      `ticket/${route.params.id}/update`,
      values, { authorize: true }
    )
    .then(res => {
      done(res.code === 0)
    })
}
</script>